package example.documentbased.editorModule.controller
{
	import example.documentbased.editorModule.models.EditorModuleModel;
	import example.documentbased.mainModule.models.vo.DocumentVO;
	
	import org.etherframework.common.utils.OU;
	import org.etherframework.controller.IReactiveCommand;
	import org.etherframework.controller.ReactiveCommand;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	import raix.reactive.Unit;
	
	public class UpdateDocumentCommand extends ReactiveCommand
	{
		private var _document:DocumentVO;
		private var _editorController:IEditorController;
		private var _editorModel:EditorModuleModel;
		
		public function UpdateDocumentCommand(editorController:IEditorController, 
											  editorModel:EditorModuleModel)
		{
			_editorController = editorController;
			_editorModel = editorModel;
		}
		
		public function initialize(document:DocumentVO):IReactiveCommand
		{
			_document = document;
			markAsInitialized();
			
			return this;
		}
		
		override public function observable():IObservable
		{
			var openedDoc:DocumentVO = OU.getItem(_editorModel.openedDocuments, 
				"uid", _document.uid) as DocumentVO;
			
			if (openedDoc)
			{
				openedDoc.apply(_document);
			}
			
			if (OU.areEqual(_editorModel.currentDocument, _document, "uid"))
			{
				_editorModel.currentDocument.apply(_document);
			}
			
			return Observable.value(new Unit());
		}
	}
}